package com.blacksheep.mtm.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.blacksheep.mtm.annotation.SystemControllerLog;
import com.blacksheep.mtm.common.exception.XmallException;
import com.blacksheep.mtm.common.utils.QiniuUtil;
import com.blacksheep.mtm.common.utils.ResultUtil;
import com.blacksheep.mtm.pojo.common.DataTablesResult;
import com.blacksheep.mtm.pojo.common.Result;
import com.blacksheep.mtm.pojo.manager.TbMedicine;
import com.blacksheep.mtm.pojo.manager.TbMember;
import com.blacksheep.mtm.service.MedicineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@RestController
@Api(description = "药品管理")
public class MedicineController {

    @Autowired
    private MedicineService medicineService;

    @RequestMapping(value = "/medicine/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取运单列表")
    public DataTablesResult getMedicineList(int draw, int start, int length, String searchKey, int[] state,
                                            String minDate, String maxDate,
                                            @RequestParam("search[value]") String search,
                                            @RequestParam("order[0][column]") int orderCol,
                                            @RequestParam("order[0][dir]") String orderDir) {

        //获取客户端需要排序的列
        String[] cols = {"checkbox", "medicine_id", "medicine_name", "name","manufacturer", "standard", "freezing","state"};
        String orderColumn = cols[orderCol];
        //默认排序列
        if (orderColumn == null) {
            orderColumn = "create_time";
        }
        //获取排序方式 默认为desc(asc)
        if (orderDir == null) {
            orderDir = "desc";
        }
        if (!StringUtils.isBlank(search)) {
            searchKey = search;
        }
        DataTablesResult result = medicineService.getList(draw, start, length, state, searchKey, minDate, maxDate, orderColumn, orderDir);
        return result;
    }


    @RequestMapping(value = "/medicine/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加药品")
    public Result<TbMedicine> addMedicine(TbMedicine medicine) {

        TbMedicine newTbMember = medicineService.insertMedicine(medicine);
        return new ResultUtil<TbMedicine>().setData(newTbMember);
    }

    @RequestMapping(value = "/medicine/update", method = RequestMethod.POST)
    @ApiOperation(value = "修改药品")
    public Result<TbMedicine> updateMedicine(TbMedicine medicine) {

        medicineService.updateMedicine(medicine);
        return new ResultUtil<TbMedicine>().setData(null);
    }

    @RequestMapping(value = "/medicine/del/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除药品")
    public Result<TbMedicine> deleteMedicine(@PathVariable Integer[] ids) {
        medicineService.deleteBatch(ids);
        return new ResultUtil<TbMedicine>().setData(null);
    }


    @RequestMapping(value = "/medicine/stop/{id}",method = RequestMethod.PUT)
    @ApiOperation(value = "下架药品")
    public Result<TbMedicine> stopMedicine(@PathVariable Integer id){
        TbMedicine medicine = medicineService.alertMedicineState(id,-1);
        return new ResultUtil<TbMedicine>().setData(medicine);
    }

    @SystemControllerLog(description = "上架药品")
    @RequestMapping(value = "/medicine/start/{id}",method = RequestMethod.PUT)
    @ApiOperation(value = "上架药品")
    public Result<TbMedicine> startMedicine(@PathVariable Integer id){
        TbMedicine medicine = medicineService.alertMedicineState(id,1);
        return new ResultUtil<TbMedicine>().setData(medicine);
    }

    @RequestMapping(value = "/medicine/download",method = RequestMethod.GET)
    @ApiOperation(value = "导出")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        medicineService.downloadExcel(response);
    }


    @RequestMapping(value = "/medicine/upload", method = RequestMethod.POST)
    @ApiOperation(value = "导入课程发布表")
    public Result<Object> uploadExcel(@RequestParam("file") MultipartFile files, HttpServletRequest request) {
        String title = files.getOriginalFilename();
        // 文件保存路径
        String filename= QiniuUtil.renamePic(files.getOriginalFilename());
        String type =  filename.split("\\.")[filename.split("\\.").length-1];

        if (!StringUtils.equals("xls",type) && !StringUtils.equals("xlsx",type)){
            throw new XmallException("文件格式错误,请上传excel文件");
        }
        String filePath = request.getSession().getServletContext().getRealPath("/upload")+"\\"
                + filename;
        // 转存文件
        try {
            //保存至服务器
            File file=new File((filePath));
            files.transferTo(file);
            FileInputStream inputStream = new FileInputStream(file);
            List<Object> sheetData1 = EasyExcelFactory.read(inputStream,new Sheet(1,0));
//            ExcelWriter writer = EasyExcelFactory.getWriterWithTemp(inputStream,out, ExcelTypeEnum.XLSX,true);
            //解析excel
            medicineService.insertFromExcel(sheetData1);

            //路径为文件且不为空则进行删除
            if (file.isFile() && file.exists()) {
                file.delete();
            }
          return   new ResultUtil<Object>().setData("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new XmallException("添加失败");
        }
    }
}
